package com.controller;


import com.model.VideoOrder;
import com.service.VideoOrderService;
import com.utils.JWTUtil;
import com.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("api/v1/pri/order")
public class VideoOrderController {

    @Autowired
    private VideoOrderService videoOrderService;


    /**
     * 下单
     * @param videoId
     * @return
     */
    @RequestMapping("save")
    public JsonData saveOrder(@RequestParam Integer videoId, HttpServletRequest request){
        Integer userId=getUserId(request);
        VideoOrder videoOrder=videoOrderService.saveOrder(videoId,userId);
        return videoOrder!=null?JsonData.buildSuccess(videoOrder):JsonData.buildError("下单失败");
    }

    /**
     * 用户的订单列表
     * @return
     */
    @GetMapping("list")
    public JsonData orderLists(HttpServletRequest request){
        int userId=getUserId(request);
        return JsonData.buildSuccess(videoOrderService.findOrdersByUserId(userId));
    }

    /**
     * 根据订单查询号查找
     * @param outTradeNo
     * @return
     */
    @GetMapping("out_trade_no")
    public JsonData findOrederByOutTradeNo(String outTradeNo){
        VideoOrder videoOrder=videoOrderService.findOrderByOutTradeNo(outTradeNo);
        return videoOrder!=null?JsonData.buildSuccess(videoOrder):JsonData.buildError("找不到该订单");
    }
    /**
     * 根据token找userId
     * @param request
     * @return
     */
    private Integer getUserId(HttpServletRequest request){
        String token=request.getHeader("token");
        return (Integer)JWTUtil.checkJWT(token).get("id");
    }







}
